package com.vvvtimes.demo.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.vvvtimes.demo.common.dto.RestResponse;
import com.vvvtimes.demo.domain.dto.EncoderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Slf4j
@Service
public class EncoderService {

    public RestResponse<String> base64Encoder(EncoderDTO encoderDTO) {
        RestResponse<String> result = new RestResponse<>();
        String data = encoderDTO.getData();
        String res = Base64.encode(data);
        result.setResult(res);
        return result;
    }

    public RestResponse<String> urlEncoder(EncoderDTO encoderDTO) {
        RestResponse<String> result = new RestResponse<>();
        String data = encoderDTO.getData();
        String res = URLEncodeUtil.encode(data);
        result.setResult(res);
        return result;
    }

    public byte[] qrEncoder(EncoderDTO encoderDTO) {
        try {
            String data = encoderDTO.getData();
            BufferedImage generate = QrCodeUtil.generate(data, 300, 300);
            byte[] bytes = bufferedImageToByteArray(generate);
            log.info("生成二维码成功!");
            return bytes;
        } catch (QrCodeException | IOException e) {
            log.error("发生错误！ {}！", e.getMessage());
        }
        return new byte[0];
    }

    /**
     * 将BufferedImage转换为byte[]
     * @param image
     * @return
     */
    public byte[] bufferedImageToByteArray(BufferedImage image) throws IOException{
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        return os.toByteArray();
    }


}
